package com.example.interviewrecorder.view

import android.app.DatePickerDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.interviewrecorder.LyyApplicaiton
import com.example.interviewrecorder.LyyBaseActivity
import com.example.interviewrecorder.LyyDatabase
import com.example.interviewrecorder.R
import com.example.interviewrecorder.adapter.RecordAdapter
import com.example.interviewrecorder.dao.RecordDao
import com.example.interviewrecorder.databinding.ActivityEditRecordBinding
import com.example.interviewrecorder.model.Rating
import com.example.interviewrecorder.model.Record
import com.example.interviewrecorder.utils.LyyActivityCollector
import com.example.interviewrecorder.utils.LyyLogUtil
import com.example.interviewrecorder.utils.getFormatDateStr
import com.example.interviewrecorder.utils.hideKeyboard
import com.example.interviewrecorder.utils.showToast
import com.example.interviewrecorder.viewmodel.RecordViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import java.util.Calendar

/**
 * @Description 编辑记录页面
 * @Author Yingyong Lao
 * @Date 2025/5/10 15:24
 */
class EditRecordActivity : LyyBaseActivity(), View.OnClickListener {
    private val editRecordViewModel by viewModels<RecordViewModel>()
    private val binding:ActivityEditRecordBinding by lazy{
        ActivityEditRecordBinding.inflate(layoutInflater)
    }
    private var record: Record? = null
    private val recordDao: RecordDao = LyyDatabase.getDatabase().getRecordDao()

    companion object{
        private const val TAG = "EditRecordActivity"
        fun start(record:Record){
            val currAct=LyyActivityCollector.getCurrActivity()
            val intent=Intent(currAct, EditRecordActivity::class.java)
            intent.putExtra(RecordAdapter.RECORD_KEY,record)
            currAct.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        record = intent.getParcelableExtra(RecordAdapter.RECORD_KEY)
        record?.let {
            editRecordViewModel.setTitle(it.title)
            editRecordViewModel.setContent(it.title)
            editRecordViewModel.setCorporateName(it.corporateName)
            editRecordViewModel.setDuration(it.duration)
            editRecordViewModel.setItvDate(it.itvDate)
            editRecordViewModel.setrRating(Rating.getRatingById(it.rating))
            editRecordViewModel.setCreatedTime(it.createdTime)
            editRecordViewModel.setUpdatedTime(it.updatedTime)

            binding.titleEt.setText(it.title)
            binding.contentEt.setText(it.content)
            binding.corporateNameEt.setText(it.corporateName)
            binding.durationEt.setText(it.duration)
            binding.itvDateTv.text=it.itvDate.getFormatDateStr()
            binding.ratingBar.rating=it.rating.toFloat()
        }

        initEvents()
        watch()
        computed()
    }

    private fun computed() {
        lifecycleScope.launch {
            launch {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    //使用combine操作符函数可以实现类似于小程序的computed效果
                    editRecordViewModel.title.combine(editRecordViewModel.content) { title, content ->
                        mutableListOf(title, content)
                    }.combine(editRecordViewModel.corporateName) { l, corporateName ->
                        l.plus(corporateName)
                    }.combine(editRecordViewModel.duration) { l, duration ->
                        l.plus(duration)
                    }.combine(editRecordViewModel.itvDate) { l, itvDate ->
                        l.plus(itvDate.toString())
                    }.combine(editRecordViewModel.rating) { l, rating ->
                        l.plus(rating.toString())
                    }.collectLatest {
                        LyyLogUtil.d(msg = "$it")
                        //标题、面试内容、公司名称、面试时长、面试日期都不为空，保存按钮才是启用状态
                        binding.saveBtn.isEnabled =
                            it[0].isNotEmpty() && it[1].isNotEmpty() && it[2].isNotEmpty() && it[3].isNotEmpty() && it[4] != "0"
                    }
                }
            }
        }
    }

    private fun watch() {
        lifecycleScope.launch {
            launch {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    editRecordViewModel.itvDate.collectLatest {
                        val color = if (it != 0L) getColor(R.color.lyy_light_black) else getColor(R.color.lyy_gray)
                        binding.itvDateTv.setTextColor(color)
                        if (it != 0L) {
                            binding.itvDateTv.text = it.getFormatDateStr()
                        }
                    }
                }
            }
        }
    }

    private fun initEvents() {
        binding.itvDateLl.setOnClickListener(this)
        binding.saveBtn.setOnClickListener(this)
        binding.titleEt.addTextChangedListener {
            editRecordViewModel.setTitle(it.toString())
            Log.d(TAG, "initEvents: 标题发生改变")
        }
        binding.contentEt.addTextChangedListener {
            editRecordViewModel.setContent(it.toString())
        }
        binding.corporateNameEt.addTextChangedListener {
            editRecordViewModel.setCorporateName(it.toString())
        }
        binding.durationEt.addTextChangedListener {
            editRecordViewModel.setDuration(it.toString())
        }
        binding.ratingBar.setOnRatingBarChangeListener { _, rating, _ ->
            editRecordViewModel.setrRating(
                when (rating) {
                    1.0f -> Rating.ONE_STAR
                    2.0f -> Rating.TWO_STAR
                    3.0f -> Rating.THREE_STAR
                    4.0f -> Rating.FOUR_STAR
                    5.0f -> Rating.FIVE_STAR
                    else -> Rating.FIVE_STAR
                }
            )
            binding.ratingBar.hideKeyboard()
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.itvDateLl -> {showDateDlg()
                v.hideKeyboard()
            }
            R.id.saveBtn -> saveDate()
        }
    }
    private fun showDateDlg() {
        val dlg = DatePickerDialog(this)
        dlg.setOnDateSetListener { _, year, month, dayOfMonth ->
            LyyLogUtil.d(msg = "$year,$month,$dayOfMonth")
            val calendar = Calendar.getInstance()
            calendar.set(year, month, dayOfMonth)
            editRecordViewModel.setItvDate(calendar.timeInMillis)
        }
        dlg.show()
    }

    private fun saveDate() {
        //当前登录的用户
        val currUser = LyyApplicaiton.currUser
        currUser?.let {
            val currTime = System.currentTimeMillis()
            val record = Record(
                userId = it.id,
                title = editRecordViewModel.title.value,
                content = editRecordViewModel.content.value,
                corporateName = editRecordViewModel.corporateName.value,
                duration = editRecordViewModel.duration.value,
                itvDate = editRecordViewModel.itvDate.value,
                rating = editRecordViewModel.rating.value,
                createdTime = editRecordViewModel.createdTime.value,
                updatedTime = currTime
            )
            record.id=this.record?.id?:0

            lifecycleScope.launch {
                launch(Dispatchers.IO) {
                    repeatOnLifecycle(Lifecycle.State.STARTED) {
                        kotlin.runCatching {
                            recordDao.updateRecord(record)
                        }.onSuccess {
                            runOnUiThread {
                                showToast(getString(R.string.update_success))
                            }
                        }.onFailure { throwable ->
                            LyyLogUtil.e(msg = throwable.toString())
                            showToast("${getString(R.string.save_fail_toast_text)}${throwable}")
                        }
                    }
                }
            }
        }
    }

}